<template>
    <div class="app-container">
        <levelbar></levelbar>
        <el-form label-width="120px" class="app-content" :rules="rules" :model="ruleForm" ref="ruleForm">
            <div class="box">
                <div class="appTitle"><h3>添加员工信息</h3></div>
                <div class="appTop"><P>基础信息</p></div>
                <el-row :gutter="20">
                    
                    <el-col :span="9">
                        <el-form-item label="姓名" prop="userName">
                            <el-input v-model="ruleForm.userName" placeholder="请输入名字" :maxlength="20"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9" :offset="5">
                        <el-form-item label="登录名" prop="loginName">
                            <el-input v-model="ruleForm.loginName" placeholder="请输入登录名" :maxlength="30"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="9">
                        <el-form-item label="初始密码" prop="initialPass">
                                <el-input type="password" v-model="ruleForm.initialPass"placeholder="请输入初始密码" :maxlength="20" auto-complete="off"></el-input>
                         </el-form-item>
                    </el-col>
                    <el-col :span="9" :offset="5">
                        <el-form-item label="确认密码" prop="checkPass">
                                <el-input type="password" v-model="ruleForm.checkPass" placeholder="请确认密码" :maxlength="20" auto-complete="off"></el-input>
                            </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="9">
                         <el-form-item label="角色" prop="roleId">
                           <el-select v-model="ruleForm.roleId" placeholder="请选择" style="width:100%" >
                                <el-option v-for="item in ruleForm.dataType" :key="item.pId" :label="item.sName" :value="item.pId"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="appTop"><P>负责区域</p></div>
                <div :offset="1">
                    <el-row v-for="(site,index) in ruleForm.dataAgent" :gutter="20" :key="site.key">
                                <el-row>
                                        <el-col :span="7">
                                            <el-form-item label="所选省：" :prop="'dataAgent[' + index + '].fProvinceId'" :rules="{required: true, message: '所选省不能为空', trigger: 'change'}">
                                                <!--<el-select v-model="site.fProvinceId" placeholder="请选择" style="width:100%" @change="changeProvice(site.fProvinceId,index)">
                                                    <el-option v-for="item in ruleForm.province" :key="item.provinceId" :label="item.provinceName" :value="item.provinceId">
                                                    </el-option>
                                                </el-select>-->
                                                <province v-model="site.fProvinceId" ></province>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="7">
                                            <el-form-item label="所选市：">
                                                <!--<el-select v-model="site.fCityId" placeholder="请选择" style="width:100%" @change="changeCityId(site.fCityId,index)">
                                                    <el-option v-for="item in site.findCity" :key="item.cityId" :label="item.cityName" :value="item.cityId">
                                                    </el-option>
                                                </el-select>-->
                                                <city v-model="site.fCityId" :province="site.fProvinceId"></city>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="7">
                                            <el-form-item label="所选区县：">
                                                <!--<el-select v-model="site.fAreaId" placeholder="请选择" style="width:100%">
                                                    <el-option v-for="item in site.findArea" :key="item.areaId" :label="item.areaName" :value="item.areaId">
                                                    </el-option>
                                                </el-select>-->
                                                <region v-model="site.fAreaId" :city="site.fCityId"></region>
                                            </el-form-item>
                                     </el-col>
                                     <div class="delBtn"><i class="el-icon-delete" @click.prevent="removeDomain(index)" v-if='index != 0'></i></div>
                                </el-row>
                    </el-row>    
                    <div style="margin-left:55px">
                        <el-button type="primary" @click="addArea"><i class="el-icon-plus"></i>继续添加</el-button>
                    </div>
                </div>
                <el-form-item class="footer">
                    <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
                    <el-button @click="resetForm">取消</el-button>
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script>
import Levelbar from '../layout/Levelbar';
import { saveCompanyStaff, findAccountIsExist, findSysRoles, findAgentAreaByOrgUserId} from 'api/staffManagement';
import { queryAllProvince, queryAllCityByProvinceId, queryAllAreaByCityId} from 'api/common';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import { mapGetters } from 'vuex';
export default{
    components: {Levelbar, province, city, region},
    data() {
        // 密码一致判断
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                if (this.ruleForm.checkPass !== '') {
                    this.$refs.ruleForm.validateField('checkPass');
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.ruleForm.initialPass) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        // 登录名判断重复
        var loginUserName = (rule, value, callback) => {
            if (value =='') {
                callback(new Error('请输入登录名'));
            } else {
                findAccountIsExist(value).then(response => {
                    if (response.data.errorMsg =='登录名已存在') {               
                        callback(new Error('登录名已存在'));
                    } else {
                        callback();
                    }
                }) 
            }
        };
        return {
            ruleForm: {
                userName: '', // 用户名
                loginName: '', // 登录名
                initialPass: '', // 密码
                checkPass: '', // 确认密码
                // type: [],
                roleId: '', // 角色
                findCity: [], // 市列表
                findArea: [], // 区列表
                province: [], // 省列表
                dataType: [], // 角色列表
                dataAgent: [
                    {
                        fProvinceId: '',
                        fCityId: '',
                        fAreaId: '',
                        findCity: [],
                        findArea: []
                    }
                ]
                
            },
            rules: {
                userName: [
                    {required: true, message: '请填写姓名', trigger: 'blur'}
                ],
                loginName: [
                    {required: true, message: '', validator: loginUserName, trigger: 'blur' }
                ],
                initialPass: [
                    {required: true, message: '', validator: validatePass, trigger: 'blur' }
                ],
                checkPass: [
                    {required: true, message: '', validator: validatePass2, trigger: 'blur' }
                ],
                roleId: [
                    {required: true, message: '角色不能为空', trigger: 'change'}
                ]
            }
        }
    },
    created() {
        this.searchProvice();
        this.getroleType();
        this.searchInfo();
        
    },
    computed: {
        ...mapGetters([
            'uid'
        ])
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    
                    this.$confirm('确定要提交吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        var dataAgentList = []
                        for (let i = 0;i< this.ruleForm.dataAgent.length;i++) {
                            let obj = {
                                fProvinceId: this.ruleForm.dataAgent[i].fProvinceId,
                                fCityId: this.ruleForm.dataAgent[i].fCityId,
                                fAreaId: this.ruleForm.dataAgent[i].fAreaId
                            }
                            dataAgentList.push(obj)
                        }
                        saveCompanyStaff(
                                this.ruleForm.userName,
                                this.ruleForm.loginName,
                                this.ruleForm.password,
                                this.ruleForm.roleId,
                                dataAgentList
                        ).then(response => {
                            if (response.data.status==200) {
                                this.$message({
                                    type: 'success',
                                    message: '添加成功!'
                                })
                                this.$router.push({name: '公司员工管理'});
                            } else {
                                this.$message({
                                    type: 'warning',
                                    message: response.data.errorMsg
                                })
                            }
                        });
                    })
                } else {
                    return false;
                }
            });
        },
        // 角色查询
        getroleType() {
            findSysRoles().then(response => {
                let roleId = response.data.content;
                let select = {
                    sName: '请选择',
                    pId: ''
                }
                roleId.unshift(select);
                this.ruleForm.dataType = roleId;
            });
        },
        // 省市区选择
        searchProvice() {
            queryAllProvince().then(response => {
                let findProvice = response.data.content;
                let select = {
                    provinceName: '请选择',
                    provinceId: ''
                }
                findProvice.unshift(select);
                this.ruleForm.province = findProvice;
            });
        },
        changeProvice(provinceId, index) {
            this.ruleForm.dataAgent[index].findCity = [];
            this.ruleForm.dataAgent[index].findArea = [];
            this.ruleForm.dataAgent[index].fCityId = '';
            this.ruleForm.dataAgent[index].fAreaId = '';
            queryAllCityByProvinceId(provinceId).then(response => {
                if (provinceId=='') {
                    return;
                }
                let findCity = response.data.content;
                let select = {
                    cityName: '请选择',
                    cityId: ''
                }
                findCity.unshift(select);
                this.ruleForm.dataAgent[index].findCity = findCity;
            });
        },
        changeCityId(cityId, index) {
            this.ruleForm.dataAgent[index].findArea = [];
            this.ruleForm.dataAgent[index].fAreaId = '';
            queryAllAreaByCityId(cityId).then(response => {
                if (cityId=='') {
                    return;
                }
                let findArea = response.data.content;
                let select = {
                    areaName: '请选择',
                    areaId: ''
                }
                findArea.unshift(select);
                this.ruleForm.dataAgent[index].findArea = findArea;
            });
        },
        // 查询省市区
        searchInfo() {

            findAgentAreaByOrgUserId(this.$route.params.orgUserId).then(response => {
                if (response.data.status==200) {
                    this.ruleForm.fProvinceId = response.data.content.provinceId;
                    this.ruleForm.fCityId = response.data.content.cityId;
                    this.ruleForm.fAreaId = response.data.content.areaId;
                } else {
                    this.$message({
                        type: 'warning',
                        message: response.data.errorMsg
                    })
                }
            });
        },
        // 添加负责区域
        addArea() {
            let area = {
                fProvinceId: '',
                fCityId: '',
                fAreaId: '',
                findCity: [],
                findArea: []
            };
            this.ruleForm.dataAgent.push(area);
        },

        // 删除添加负责区域
        removeDomain(index) {
            this.ruleForm.dataAgent.splice(index, 1);
        },
    // 跳转
          // 取消
        resetForm() {
            this.$router.push({name: '公司员工管理'});
        }  
    
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    position: relative;
    padding: 20px 20px 10px;
    .app-levelbar {
        height: 35px;
    }
    .el-form{
        padding-Top:30px;
        background:#fff;
        padding-bottom:170px;
        .appTop{
            padding:40px 0 20px 50px;
            margin-bottom:10px;
            position:relative;
        }
        .appTop p{
            margin-left:15px;
        }
        .el-form-item{
            margin-top:8px;
        }
        .appTop:before {
            content: '';           
            float: left;
            border-radius: 2px;
            width:4px;height:20px;
            background:#ff5e2c;
            margin-top:1px;
        }
        .addContinue{
            margin-left:60px;
            margin-top:20px
        }
        .appTitle{
            padding:40px 0 30px 50px;
            margin-bottom:30px;
            padding-top:10px;
            text-align:center;
            border-bottom:1px solid #ECECEC
        }
        .box{
            margin-left:20px;
            padding-bottom:10px;
            background:#fff;
           .delBtn {
                display: inline-block;
                height: 36px;
                width: 16px;
                color:#999;
                line-height: 56px;
                margin-left:25px;
                i {
                    cursor: pointer;
                }

            }    
        
        }

        .footer{
            text-align:center;
            margin-top:150px;
        }
        .footer .el-button{
            padding:10px 40px;
        }
    }
    
}

</style>